package com.oigx.lookmu;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsContexts;
import com.oigx.lookmu.core.SettingsState;
import com.oigx.lookmu.core.TxtBook;
import com.oigx.lookmu.core.TxtReaderUtil;
import com.oigx.lookmu.ui.SettingFrame;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.List;

public class SettingFactory implements SearchableConfigurable {

    private final Project project;
    private final SettingFrame settingFrame = new SettingFrame();
    SettingsState settingsState = SettingsState.getInstance();

    public SettingFactory(Project project) {
        this.project = project;
    }

    @Override
    public @NotNull @NonNls String getId() {
        return "lookMuSettings";
    }

    @Override
    public @NlsContexts.ConfigurableName String getDisplayName() {
        return "test-cfg";
    }

    /**
     * 获取设置区域要展示的信息，这里返回我们的panel
     */
    @Override
    public @Nullable JComponent createComponent() {
        return settingFrame.getRootComponent();
    }

    @Override
    public boolean isModified() {
        return true;
    }

    /**
     */
    @Override
    public void apply() throws ConfigurationException {
        System.out.println(settingFrame.getFilePath());
        settingsState.filePath = settingFrame.getFilePath();
        if (StringUtils.isNotBlank(settingFrame.getLineMaxChar())){
            if (settingFrame.getLineMaxChar().matches("[1-9][0-9]{1,2}")){
                settingsState.lineMaxChar = Integer.parseInt(settingFrame.getLineMaxChar());
            } else {
                System.out.println("xxx");
            }
        }
        if (StringUtils.isNotBlank(settingsState.filePath)){
            List<TxtBook> bookList = TxtReaderUtil.loadBook(settingsState.filePath) ;
            System.out.println("updateBookList");
            this.settingsState.bookList = bookList;
        }
        settingsState.fileIndex = 0;
        settingsState.chapterList = null;
        settingsState.chapterIndex = 0;
        settingsState.readLine = 0;
        settingsState.readLineList = null;
        LookMuFactory.initLookDialog(project).initFileList();
    }



}
